/** yipaidingcan
 * - 余额 {云对象} 余额系列操作
 *  第三方技术支持来自uniCloud云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
 * jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
 * @param tel 17664189378 冀**
 */

//生成唯一订单号方法
function setOutTradeNo(letter) {
	const date = new Date(); // 当前日期
	const outTradeNo = letter + date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate() + '' + date
		.getHours() + '' + date.getMinutes() + '' + date.getSeconds(); // 根据当前日期生成订单号的前缀部分
	const random = Math.round(Math.random() * 100) + '' + Math.round(Math.random() * 100) + '' + Math.round(Math
		.random() * 100); // 生成随机数部分
	return outTradeNo + '' + random; // 返回完整的订单号
}

module.exports = {
	_before: function() { // 通用预处理器
	},
	/**
	 * 获取可提现金额数据方法
	 * @param {string} shopId 店铺Id
	 * @param {string} threeDaysAgoTimestamp 三天前的时间戳
	 * @returns {object} 返回包含处理结果的对象
	 */
	async getWithdrawable(shopId) {
		// 参数校验
		if (!shopId) {
			return {
				error: '参数不完整',
				code: 400
			};
		}
		const dbjql = uniCloud.databaseForJQL()
		const db = uniCloud.database();
		const dbCmd = db.command;
		//三天前的时间戳
		const today = new Date(); // 获取当前日期
		const threeDaysAgo = new Date(today.getTime() - 3 * 24 * 60 * 60 * 1000); // 通过减去 3 天的毫秒数获取三天前的日期
		const threeDaysAgoTimestamp = threeDaysAgo.getTime();
		try {
			// 查询三天前可提现账单
			const queryResult = await dbjql.collection("shop_bill").where(
				`shop_id=='${shopId }' && create_date < ${threeDaysAgoTimestamp}  && is_account != ${true} && bank == null `
			).orderBy("create_date", "desc").field("price, type, is_account").limit(9999).get();
			// 处理查询结果
			if (queryResult && queryResult.data && queryResult.data.length > 0) {
				let withdrawableMoney = 0;
				const accountIds = queryResult.data.map(item => {
					if (item.type === 1) {
						withdrawableMoney += item.price;
					} else if (item.type === 2) {
						withdrawableMoney -= item.price;
					}
					return item._id; // 返回需修改店铺账单的ID
				});
				// 更新店铺可提现金额
				await db.collection('shop').where({
					_id: shopId
				}).update({
					withdrawable_money: dbCmd.inc(withdrawableMoney)
				})
				// 批量修改店铺账单
				await db.collection("shop_bill").where({
					_id: dbCmd.in(accountIds)
				}).update({
					is_account: true
				});
				// 返回最新账单可提现余额
				var result = await dbjql.collection("shop").where({
					_id: shopId
				}).field("withdrawable_money,money,_id").get({
					getOne: true
				})

				return {
					error: '操作成功',
					setAccountIds: accountIds,
					code: 200,
					result: result.data,
				};

			} else {
				// 返回最新账单可提现余额
				var result = await dbjql.collection("shop").where({
					_id: shopId
				}).field("withdrawable_money,money,_id").get({
					getOne: true
				})
				return {
					error: '无新数据',
					code: 200,
					result: result.data,
				};
			}
		} catch (err) {

			return {
				error: '内部错误',
				code: 500,
				message: err,
			};

			dbJQL.collection('users_log').add({
				type: 2,
				text: `店铺${shopId},在‘获取可提现金额’方法时发生错误：${err}`
			})
		}
	},
	/**
	 * - 余额提现 方法
	 * @param {string} shopId 店铺Id
	 * @param {object} deductBalance 将要扣除の余额&服务费
	 * @param {object} bankCardData 银行卡 数据
	 * @returns {object} 返回包含处理结果的对象
	 */
	async eventBalanceWithdraw(shopId, deductBalance, bankCardData) {
		// 参数校验
		if (!shopId || !deductBalance || !bankCardData) {
			return {
				error: '参数不完整',
				code: 400,
				shopId,
				deductBalance,
				bankCardData
			};
		}
		const dbjql = uniCloud.databaseForJQL()
		const db = uniCloud.database();
		try {
		// 查询店铺数据
			const shopData = await dbjql.collection("shop").where({_id: shopId}).field("title,_id,money,withdrawable_money").get({getOne: true})
		// 查询银行卡数据
			const BankData = await dbjql.collection("users_bank").doc(bankCardData._id).field("user_id,shop_id,bank_tel,name,bank_type,bank_no,bank_title,_id").get({getOne: true})
			let tempBank = BankData.data
		// 重构 bankTitle
			tempBank.bank_title = [ {label: BankData.data.bank_title}  ]
			// 重新构建将要扣除の金额/服务费
			let deductMoney = {
				deductBalance: Math.round(deductBalance.deductBalance * 100),
				serviceMoney: Math.round(deductBalance.serviceMoney * 100)
			}
			// 计算本次需从余额中减去多少钱
			let Balance = Math.round(deductMoney.deductBalance + deductMoney.serviceMoney)
			if (shopData.data.withdrawable_money < Balance || shopData.data.money < Balance) {
				return {
					code: 1005,
					error: "余额不足",
					shopData
				}
			}
			// 扣除商铺可提现余额&余额
			await db.collection('shop').where({_id: shopId}).update({withdrawable_money: db.command.inc(-Balance),money: db.command.inc(-Balance) })
			let Data = { // 构建 出shop-bill表 提现支出数据
				create_date: new Date().getTime(),
				shop_id: shopId,
				is_account: true,
				type: 2,
				shop: {
					_id: shopId,
					title: shopData.data.title,
				},
				order: {
					order_no: setOutTradeNo("R"),
					total_fee: deductMoney.deductBalance,
				},
				bank: {
					title: "银行卡信息",
					serve_money: deductMoney.serviceMoney / 100,
					create_time: new Date().getTime(),
					properties: tempBank
				},
				is_settlement: {
					is_true: false,
					create_time: new Date().getTime()
				},
				user: {
					nickname: "易派商家",
					avatar: "https://mp-60d04191-dfc8-47dc-b1e1-36d6fc279352.cdn.bspapp.com/icons/shop_logo.png"
				},
				price: deductMoney.deductBalance,
				text: "提现支出"
			}
			let addShopBill = await dbjql.collection("shop_bill").add(Data)
			return {
				code: 200,
				error: "操作成功",
				result: addShopBill
			}
		} catch (err) {
			dbjql.collection('users_log').add({
				type: 2,
				text: `店铺${shopId},在‘确认提现申请’方法发生错误：${err}`
			})
			return {
				code: 501,
				error: "内部错误",
				message: err
			}

		}
	}

}